package com.ps.service.setting.imp;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.oscache.util.StringUtil;
import com.ps.dao.BaseDaoSupport;
import com.ps.dao.setting.UnqueNumberDAO;
import com.ps.entity.Result;
import com.ps.pojo.setting.UnqueNumber;
import com.ps.service.BaseServiceSupport;
import com.ps.service.setting.UnqueNumberService;

public class UnqueNumberServiceImp extends BaseServiceSupport<UnqueNumber>
		implements UnqueNumberService {
	
	@Autowired
	private UnqueNumberDAO unqueNumberDAO;


	public String increaseCodeValue(String nameCode) {
        Session session = null;
        Transaction tx = null;
        try {
        	session = unqueNumberDAO.getSessionFactory().openSession();
        	Criteria criteria = session.createCriteria(UnqueNumber.class);
        	criteria.add(Restrictions.eq(UnqueNumberDAO.NAME_CODE, nameCode));
		    List list = criteria.list();
		    if (list == null || list.size() <= 0) {
		    	session.close();
		    	return null;
		    }
		    UnqueNumber unqueNumber = (UnqueNumber) list.get(0);
			tx = session.beginTransaction();
			Long codeValue = unqueNumber.getCodeValue() + 1;
			unqueNumber.setCodeValue(codeValue);
			String prefix = "";
			String suffix = "";
			String middle = codeValue.toString();
			int size = unqueNumber.getCodeMaxLengh().intValue() ;
			if (StringUtils.isNotEmpty(unqueNumber.getPrefix())) {
				prefix = unqueNumber.getPrefix();
			}
			
			if (StringUtils.isNotEmpty(unqueNumber.getSuffix())) {
				suffix = unqueNumber.getSuffix();
			}
			
			size = size - prefix.length() - suffix.length();
			tx.commit();
			session.close();
			return prefix +  StringUtils.leftPad(middle, size, '0')  + suffix;
		} catch (Exception e) {
			if (tx != null) tx.rollback();
			if (session != null) session.close();
			log.error("increaseCodeValue exception ", e);
		}
        
		return null;
	}

	@Override
	public BaseDaoSupport<UnqueNumber> getBaseDao() {
		// TODO Auto-generated method stub
		return unqueNumberDAO;
	}


}
